Largest Number

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

Solution:

  1. public class Solution {
  2. public String largestNumber(int[] num) {
  3. int n = num.length;
  4. Integer[] A = new Integer[n];
  5. for (int i = 0; i < n; i++) {
  6. A[i] = Integer.valueOf(num[i]);
  7. }
  8. // sort the array by string
  9. Arrays.sort(A, new Comparator<Integer>() {
  10. @Override
  11. public int compare(Integer a, Integer b) {
  12. String stra = String.valueOf(a);
  13. String strb = String.valueOf(b);
  14. return (strb + stra).compareTo(stra + strb);
  15. }
  16. });
  17. StringBuilder sb = new StringBuilder();
  18. for (int i = 0; i < n; i++) {
  19. if (A[i] == 0 && sb.length() == 0) {
  20. continue;
  21. }
  22. sb.append(String.valueOf(A[i]));
  23. }
  24. if (sb.length() == 0) {
  25. return "0";
  26. }
  27. return sb.toString();
  28. }
  29. }